package com.hk.db;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.hk.R;
import com.hk.model.Question;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DBHelper extends OrmLiteSqliteOpenHelper {

	private static final String DB_Name = "question.db";
	private static final String File_PATH = android.os.Environment.getExternalStorageDirectory().getAbsolutePath()
			+ File.separator
			+ "ExameStore";
	private static final String DB_File = File_PATH + File.separator + DB_Name;
	static DBHelper instance;

	private Dao<Question, Integer> questionDao;

	public DBHelper(Context context) {
		super(context, DB_File, null, 1);
	}

	@Override
	public void onCreate(SQLiteDatabase database,
			ConnectionSource connectionSource) {
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, ConnectionSource arg1, int arg2,
			int arg3) {
	}

	/**
	 * 单例获取该Helper
	 * 
	 * @param context
	 * @return
	 */
	public static synchronized DBHelper getHelper(Context context) {
		if (instance == null) {
			synchronized (DBHelper.class) {
				if (instance == null)
					instance = new DBHelper(context);
			}
		}
		return instance;
	}

	/**
	 * 释放资源
	 */
	@Override
	public void close() {
		super.close();
		questionDao=null;
	}

	/*
	 * 获取单利
	 */
	public Dao<Question, Integer> getQuestionDao() throws java.sql.SQLException {
		if (questionDao == null) {
			questionDao = getDao(Question.class);
		}
		return questionDao;
	}

	/**
	 * 数据库拷贝
	 * 
	 * @param context
	 * @return
	 */
	public static Boolean copyDB(Context context) {
		try {
			int BUFFER_SIZE = 400000;
			InputStream is = context.getResources().openRawResource(
					R.raw.question);
			File file = new File(File_PATH);
			if (!file.exists())
				file.mkdir();
			FileOutputStream fos = new FileOutputStream(DB_File);
			byte[] buffer = new byte[BUFFER_SIZE];
			int count = 0;
			while ((count = is.read(buffer)) > 0) {
				fos.write(buffer, 0, count);
			}
			fos.close();
			is.close();
			return true;
		} catch (FileNotFoundException e) {
			Log.e("Database", "File not found");
			e.printStackTrace();
		} catch (IOException e) {
			Log.e("Database", "IO exception");
			e.printStackTrace();
		}
		return false;
	}

}
